#include "FileSendAndRecevie.h"
#include <QTime>

FileSendAndRecevie::FileSendAndRecevie()
{
}

QString FileSendAndRecevie::createPluginMenu()
{
	return tr("network/fileSendAndRev");
}

void FileSendAndRecevie::createPluginMenuResult(bool result, QString menuId, QString error)
{

}

QWidget* FileSendAndRecevie::createPluginWidget()
{
	if (m_panel == nullptr)
	{
        m_panel = new FileSendAndReceviePanel();
	}
	return m_panel;
}

void FileSendAndRecevie::destroyPluginWidget()
{
	if (m_panel)
	{
		delete m_panel;
		m_panel = nullptr;
	}
}



//////////////////////////////////////////
TcpServer::TcpServer(QObject* parent)
{
	connect(this, &QTcpServer::newConnection, this, &TcpServer::onNewConnection);
}

void TcpServer::onNewConnection()
{
	QTcpSocket* socket = this->nextPendingConnection();
	connect(socket, &QTcpSocket::readyRead, this, [this, socket]() {socket->readAll(); });
	connect(socket, &QTcpSocket::disconnected, this, [this, socket]() {socket->deleteLater(); });
}

void TcpServer::onRevMessage(QTcpSocket* socket)
{

}


//////////////////////////////////////////
#include <QVBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QThread>
FileSendAndReceviePanel::FileSendAndReceviePanel(QWidget* parent)
	:QFrame(parent)
{
	m_revServer = new TcpServer(this);
	//connect(m_revServer, &QTcpServer::newConnection, this, &FileSendAndReceviePanel::onNewConnection);
	if (!m_revServer->listen(QHostAddress::Any, 8888))
	{
		Q_ASSERT(false);
	}
	QThread* thread = new QThread();
	m_revServer->moveToThread(thread);
    thread->start();

	QVBoxLayout* mainLayout = new QVBoxLayout(this);

	{
		QLabel* label = new QLabel(tr("revFilePath:"), this);
		m_revFilePathEdit = new QLineEdit(this);
		m_revFilePathEdit->setText("E:\\video2.avi");
		QHBoxLayout* hLayout = new QHBoxLayout();
		hLayout->setContentsMargins(0, 0, 0, 0);
		hLayout->addWidget(label);
		hLayout->addWidget(m_revFilePathEdit);
		mainLayout->addLayout(hLayout);
	}

	{
		QLabel* label = new QLabel(tr("sendFilePath:"), this);
		m_sendFilePathEdit = new QLineEdit(this);
		m_sendFilePathEdit->setText("E:\\video1.avi");
		QPushButton* button = new QPushButton(tr("send"), this);
		QHBoxLayout* hLayout = new QHBoxLayout();
		hLayout->setContentsMargins(0, 0, 0, 0);
		hLayout->addWidget(label);
		hLayout->addWidget(m_sendFilePathEdit);
		hLayout->addWidget(button);
		mainLayout->addLayout(hLayout);

		connect(button, &QPushButton::clicked, this, &FileSendAndReceviePanel::onSendButtonClicked);
	}

	{
		QLabel* label = new QLabel(tr("sendProgress:"), this);
		m_sendProgressBar = new QProgressBar(this);
		QHBoxLayout* hLayout = new QHBoxLayout();
		hLayout->setContentsMargins(0, 0, 0, 0);
		hLayout->addWidget(label);
		hLayout->addWidget(m_sendProgressBar);
		mainLayout->addLayout(hLayout);
		m_sendProgressBar->setRange(0, 100);
	}


	{
		QLabel* label = new QLabel(tr("revProgress:"), this);
		m_revProgressBar = new QProgressBar(this);
		QHBoxLayout* hLayout = new QHBoxLayout();
		hLayout->setContentsMargins(0, 0, 0, 0);
		hLayout->addWidget(label);
		hLayout->addWidget(m_revProgressBar);
		mainLayout->addLayout(hLayout);
		m_revProgressBar->setRange(0, 100);
	}
}

void FileSendAndReceviePanel::onNewConnection()
{
	QTcpSocket* socket = m_revServer->nextPendingConnection();
	connect(socket, &QTcpSocket::readyRead, this, [this, socket]() {onRevMessage(socket); });
	connect(socket, &QTcpSocket::disconnected, this, [this, socket]() {onDisconnected(socket); });
}

void FileSendAndReceviePanel::onRevMessage(QTcpSocket* socket)
{
	if (m_revFile == nullptr)
	{
		m_revFile = new QFile();
		QString filePath = m_revFilePathEdit->text();
		m_revFile->setFileName(filePath);
		if (!m_revFile->open(QIODevice::WriteOnly))
		{
			delete m_revFile;
			m_revFile = nullptr;
		}
	}
	if (m_revFile != nullptr)
	{
		m_revFile->write(socket->readAll());
		m_revFile->flush();
		if (m_revFile->pos() * 100 / m_sendFileSize > 10)
			m_revProgressBar->setValue(m_revFile->pos() * 100 / m_sendFileSize);
	}
}

void FileSendAndReceviePanel::onDisconnected(QTcpSocket* socket)
{
	if (m_revFile != nullptr)
	{
		m_revFile->close();
		delete m_revFile;
		m_revFile = nullptr;
	}
}

void FileSendAndReceviePanel::onSendButtonClicked()
{
	if (m_sendSocket == nullptr)
	{
		m_sendSocket = new QTcpSocket(this);
		connect(m_sendSocket, &QTcpSocket::connected, [this]() {
			QString filePath = m_sendFilePathEdit->text();
			m_sendFile = new QFile(filePath);
			if (!m_sendFile->open(QIODevice::ReadOnly))
			{
				return;
			}
			m_sendFileSize = m_sendFile->size();
			//for (int i = 0; i < 10000; i++)
			{
				sendFileData();
			}
		});
		connect(m_sendSocket, &QTcpSocket::errorOccurred,[this](QAbstractSocket::SocketError error) {
			m_sendSocket->close();
			delete m_sendSocket;
			m_sendSocket = nullptr;
		});
		connect(m_sendSocket, &QTcpSocket::disconnected, this, [this]() {
			delete m_sendSocket;
			m_sendSocket = nullptr;
		});
		connect(m_sendSocket, &QTcpSocket::bytesWritten, this, [this]() {
			sendFileData();
		});
		m_sendSocket->connectToHost("192.168.1.95", 8888);
	}
}

void FileSendAndReceviePanel::sendFileData()
{
	if (m_sendFile == nullptr || m_sendSocket == nullptr)
		return;
	if (m_sendCount == 0)
	{
		m_sendStartMsec = QTime::currentTime().msecsSinceStartOfDay();
	}
	m_sendCount++;
	if (m_sendCount == 1000)
	{
		qInfo() << "sendCount == 1000 need msec: " << (QTime::currentTime().msecsSinceStartOfDay() - m_sendStartMsec);
	}
	static int onceSize = 1024 * 1024;
	qint64 pos = m_sendFile->pos();
	qint64 remianSize = m_sendFile->size() - m_sendFile->pos();
	m_sendSocket->write(m_sendFile->read(remianSize > onceSize ? onceSize : remianSize));
	if (m_sendFile->pos() * 100 / m_sendFileSize > 10)
		m_sendProgressBar->setValue(m_sendFile->pos() * 100 / m_sendFileSize);

	if (remianSize < onceSize)
	{
		m_sendSocket->disconnectFromHost();
	}
}